package com.timedomain.him.remake.ui;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.VibrationEffect;
import android.os.Vibrator;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.timedomain.him.remake.R;
import com.timedomain.him.remake.core.NightMode;
import com.timedomain.him.remake.service.PlayerService;
import com.timedomain.him.remake.utils.AppSettings;
import com.timedomain.him.remake.utils.BaseActivity;
import com.timedomain.him.remake.utils.MorningCallManager;
import com.timedomain.him.remake.utils.TimeUtils;
import com.timedomain.him.remake.views.NumericUpAndDown;

import org.jetbrains.annotations.Nullable;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;

public class NightActivity extends BaseActivity {

    public static void startNightMode(Context ctx){
        if(PlayerService.player != null){
            if(PlayerService.player instanceof NightMode){
                // Do Nothing.
            }
            else{
                PlayerService.StopPlayerService(ctx);
                PlayerService.StartPlayerService(ctx,new NightMode(ctx,AppSettings.filteredNightStories,AppSettings.nightModeStoryCount,AppSettings.nightModeDuration));
            }
        }
        else{
            PlayerService.StartPlayerService(ctx,new NightMode(ctx,AppSettings.filteredNightStories,AppSettings.nightModeStoryCount,AppSettings.nightModeDuration));
        }

        ctx.startActivity(new Intent(ctx,NightActivity.class));
    }


    private com.timedomain.him.remake.views.NumericUpAndDown numNightmodeMinute;
    private com.timedomain.him.remake.views.DarkWaveformView nightModeWaveform;
    private Button btnWakeUp;
    private TextView txtNightModeTimerDecoration;
    private ImageView imgMoon;
    private View nightModeSplash;
    private void initUI(){	 numNightmodeMinute = (com.timedomain.him.remake.views.NumericUpAndDown)findViewById(R.id.numNightmodeMinute);
        nightModeWaveform = (com.timedomain.him.remake.views.DarkWaveformView)findViewById(R.id.nightModeWaveform);
        btnWakeUp = (Button)findViewById(R.id.btnWakeUp);
        txtNightModeTimerDecoration = (TextView)findViewById(R.id.txtNightModeTimerDecoration);
        imgMoon = (ImageView)findViewById(R.id.imgMoon);
        nightModeSplash = (View)findViewById(R.id.nightModeSplash);
    }

    private void showNextTime(){
        long nextTime = MorningCallManager.getNextTime();
        if(nextTime == -1){
            ((TextView)findViewById(R.id.txtGetUpTime)).setText("");
            return;
        }
        long dateStamp = TimeUtils.toDateStamp(nextTime);
        long todayDateStamp = TimeUtils.toDateStamp(TimeUtils.getTimeStampIgnoreTimeZone());
        String morningCallTime = new SimpleDateFormat("HH:mm", Locale.US).format(
                new Date(TimeUtils.toSystemTimeStamp(
                        nextTime
                ))
        );
        ((TextView)findViewById(R.id.txtGetUpTime)).setText("起床 " + morningCallTime);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_nightmode);
        initUI();

        numNightmodeMinute.setMaxValue(AppSettings.nightModeDuration);
        numNightmodeMinute.setValue(AppSettings.nightModeDuration);
        numNightmodeMinute.setUserChangedValueListener(this::onTimeChanged);
        if(PlayerService.player != null){
            if(PlayerService.player instanceof NightMode){

            }
            else{
                finish();
            }
        }
        else{
            finish();
        }
        setTimerEnabled(true);
        showNextTime();
        setTimerInterval(50);
    }

    boolean lastFallAsleep = false;
    boolean lastFallAsleepUpdate = false;
    @Override
    protected void onTimer() {

        if(PlayerService.player == null || !(PlayerService.player instanceof NightMode)){
            finish();
            return;
        }
        NightMode player = (NightMode)PlayerService.player;
        nightModeWaveform.Amplitude = player.getPeak();
        numNightmodeMinute.setValue(player.getCurrentMinutes());

        if(lastFallAsleep != player.isFallAsleep() || lastFallAsleepUpdate){
            lastFallAsleepUpdate = true;
            lastFallAsleep = player.isFallAsleep();

            numNightmodeMinute.setVisibility(lastFallAsleep ? View.INVISIBLE : View.VISIBLE);
            btnWakeUp.setVisibility(lastFallAsleep ? View.VISIBLE : View.INVISIBLE);
            imgMoon.setVisibility(lastFallAsleep ? View.VISIBLE : View.INVISIBLE);
            txtNightModeTimerDecoration.setText(lastFallAsleep ? R.string.night_timer_pointer_after : R.string.night_timer_pointer_before);
        }
        if(wakeSplash > 0.0001){
            nightModeSplash.setAlpha(wakeSplash);
            wakeSplash -= 0.03;
            if(wakeSplash < 0){
                wakeSplash = 0;
                nightModeSplash.setAlpha(0);
            }
        }
    }


    public void onTimeChanged(NumericUpAndDown view, int newValue) {
        if(PlayerService.player == null || !(PlayerService.player instanceof NightMode)){return;}
        NightMode player = (NightMode)PlayerService.player;
        player.setCurrentMinute(newValue);
    }

    long lastClick = -1;
    float wakeSplash = 0f;

    public void wakeHimUp(View view) {
        wakeSplash = 1.0f;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            ((Vibrator)getSystemService(VIBRATOR_SERVICE)).vibrate(VibrationEffect.createOneShot(233,VibrationEffect.DEFAULT_AMPLITUDE));
        }
        else{
            ((Vibrator)getSystemService(VIBRATOR_SERVICE)).vibrate(233);
        }
        if(System.currentTimeMillis() - lastClick > 1000){
            showToast( "再戳一次唤醒");
            lastClick = System.currentTimeMillis();
            return;
        }

        if(PlayerService.player == null || !(PlayerService.player instanceof NightMode)){return;}
        NightMode player = (NightMode)PlayerService.player;
        view.setVisibility(View.INVISIBLE);
        player.wakeUp();
    }

    @Override
    public void onBackPressed() {
        endNightMode(null);
        super.onBackPressed();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

    }

    public void endNightMode(View view) {
        if(PlayerService.player != null && PlayerService.player instanceof NightMode){
            PlayerService.player.close();
            PlayerService.player = null;
            PlayerService.StopPlayerService(this);
        }
        if(view != null){
            finish();
        }
    }


    public void debugNightMode(View view) {
        if(PlayerService.player != null && PlayerService.player instanceof NightMode){
            NightMode nightMode = (NightMode) PlayerService.player;
            nightMode.setPosition(nightMode.getDuration() - 4000);
        }
    }
}
